#pragma once

#include <iostream>
#include "Socket.hpp"
#include "Connection.hpp"
#include "Common.hpp"
#include "Channel.hpp"
#include "Reactor.hpp"

using namespace SocketModule;

// 该类的功能:专门获取新链接
class Listener : public Connection
{
public:
    Listener(int port = defaultport)
        : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
        SetEvent(EPOLLIN | EPOLLET);
        SetNonBlock(_listensock->Fd());
        // SetFd(_listensock->Fd());
    }
    ~Listener()
    {
    }
    void Recver()
    {
        // LOG(LogLevel::DEBUG) << "进入Listener模块的Recver函数";
        InetAddr client;
        while (true)
        {
            int sockfd = _listensock->Accept(&client);
            if (sockfd == ACCEPT_ERR)
                break;
            else if (sockfd == ACCEPT_CONTINUE)
                continue;
            else if (sockfd == ACCEPT_DONE)
                break;
            else
            {
                std::shared_ptr<Connection> conn = std::make_shared<Channel>(sockfd, client);
                conn->SetEvent(EPOLLIN | EPOLLET);
                if (_handler != nullptr)
                    conn->RegisterHandler(_handler);
                GetOwner()->AddConection(conn);
            }
        }
    }
    void RegisterHandler(handler_t handler)
    {
    }
    void Sender() override
    {
    }
    void Excepter() override
    {
    }
    int GetFd() override
    {
        return _listensock->Fd();
    }
   
private:
    int _port;
    std::unique_ptr<Socket> _listensock;
};